package com.efast.cafe.portal.controller.query;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.efast.cafe.commponent.query.service.IQueryService;
import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.controller.AbstractController;
import com.efast.cafe.framework.enums.ResultStatus;
import com.efast.cafe.framework.util.QueryStringUtil;
import com.efast.cafe.framework.util.SqlFormateUtil;
import com.efast.cafe.framework.vo.DataTableVo;
import com.efast.cafe.portal.bean.query.QueryBean;
import com.efast.cafe.portal.bean.query.TemplateBean;
import com.efast.cafe.portal.bean.query.TemplateObjBean;
import com.efast.cafe.portal.bean.query.TemplateSaveBean;
import com.efast.cafe.portal.entity.query.Template;
import com.efast.cafe.portal.entity.query.TemplateJsonObj;
import com.efast.cafe.portal.entity.query.TemplateObj;
import com.efast.cafe.portal.entity.query.TemplateSave;
import com.efast.cafe.portal.service.query.IQueryTemplateService;
import com.efast.cafe.portal.service.query.ITemplateParseService;
import com.efast.cafe.util.StringUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/frame_center/query")
public class QueryTemplateController extends AbstractController{
	@Autowired
	private IQueryTemplateService queryTemplateService;
	@Autowired
	private ITemplateParseService templateParseService;
	@Autowired
	@Qualifier("defaultQueryService")
	private IQueryService queryService;
	
	/**
	 * 增加模板
	 * @param request
	 * @param response
	 * @param template
	 * @param tableViews
	 * @param tableConditions
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/add")	
	public @ResponseBody ResultBean templateAdd(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody TemplateObj template){
		Template temp = null;
		String message = SqlFormateUtil.doValidation(template.getTemplate());
		if (SqlFormateUtil.SUCCESS_MESSAGE.equals(message)) {
			SqlFormateUtil.replaceBack(template.getTemplate());
			String contextPath = getContextPath(template);
			temp = queryTemplateService.addQueryTemplate(template.getTemplate(), template.getTableViews(), template.getTableConditions(),contextPath,template.getSystemId());
			return super.tipResultBean(temp.getId(), UPDATE,temp.getCode()) ;
		}
		return super.tipResultBean(0, UPDATE,QueryStringUtil.escapeJavascript(message)) ;
	}
	
	/**
	 * 模板详情
	 * @param request
	 * @param response
	 * @param templateId
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/detail")	
	public @ResponseBody ResultBean templateDetail(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody Map<String, Object> map){
		ResultBean bean = new ResultBean();
		Integer templateId = null;
		Object templateIdObj = map.get("templateId");
		if (templateIdObj instanceof Integer) {
			templateId = (Integer)templateIdObj;
		} else {
			templateId = Integer.parseInt(templateIdObj.toString());
		}
		TemplateObjBean objBean = queryTemplateService.queryTempalteDetail(templateId,null);
		bean.setMessage(objBean.getMessage());
		bean.setSuccess(objBean.isSuccess());
		bean.setObject(objBean);
		/*TestPdfGenerator generator = new TestPdfGenerator();
		try {
			File file = new File("C:\\Users\\Administrator\\Desktop\\test.csv");
			OutputStream outputStream = new FileOutputStream(file);
			outputStream.write(generator.generatePdf());
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return bean;
	}
	
	/**
	 * 修改模板
	 * @param request
	 * @param response
	 * @param template
	 * @param tableViews
	 * @param tableConditions
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/update")	
	public @ResponseBody ResultBean templateUpdate(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody TemplateObj template){
		Template temp = null;
		String message = SqlFormateUtil.doValidation(template.getTemplate());
		if (SqlFormateUtil.SUCCESS_MESSAGE.equals(message)) {
			SqlFormateUtil.replaceBack(template.getTemplate());
			String contextPath = getContextPath(template);
			temp = queryTemplateService.updateQueryTemplate(template.getTemplate(), template.getTableViews(), template.getTableConditions(),contextPath);
			return super.tipResultBean(temp.getId(), UPDATE,temp.getCode()) ;
		}
		return super.tipResultBean(0, UPDATE,QueryStringUtil.escapeJavascript(message));
	}
	
	/**
	 * 模板列表
	 * @param request
	 * @param response
	 * @param fieldTypeBean
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/list")	
	public @ResponseBody DataTableVo<TemplateBean> templateList(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody TemplateBean templateBean){
		
		return outPageJSONArray_bootstrapDatatable(queryTemplateService.queryTemplateListByPage(templateBean));
	}
	
	/**
	 * 删除模板
	 * @param request
	 * @param response
	 * @param templateId
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/delete")	
	public @ResponseBody ResultBean templateDelete(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody Map<String, Object> map){
		Integer templateId = null;
		Object templateIdObj = map.get("templateId");
		if (templateIdObj instanceof Integer) {
			templateId = (Integer)templateIdObj;
		} else {
			templateId = Integer.parseInt(templateIdObj.toString());
		}
		return super.tipResultBean(queryTemplateService.deleteQueryTemplate(templateId), DELETE) ;
	}
	
	/**
	 * 添加保存查询
	 * @param request
	 * @param response
	 * @param templateSave
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/templateCondition/add")	
	public @ResponseBody ResultBean addTemplateCondition(HttpServletRequest request, HttpServletResponse response,		
			@RequestBody  Map<String, Object> map){
		try {
			TemplateJsonObj templateSave = new TemplateJsonObj();
			templateSave.setCode((String) map.get("code"));
			templateSave.setConditionJson(JSONObject.fromObject(map.get("tableConditionJson")).toString());
			Object templateIdObj = map.get("queryTemplateId");
			if (templateIdObj instanceof Integer) {
				templateSave.setQueryTemplateId((Integer)templateIdObj);
			} else {
				templateSave.setQueryTemplateId(Integer.parseInt(templateIdObj.toString()));
			}
			
			return super.tipResultBean(queryTemplateService.addTemplateSave(templateSave),ADD,templateSave.getId());
		} catch (Exception e) {
			ResultBean bean = new ResultBean();
			bean.setMessage(e.getMessage());
			return bean;
		}
		
	}
	
	/**
	 * 添加保存查询
	 * @param request
	 * @param response
	 * @param templateSave
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/templateCondition/delete")	
	public @ResponseBody ResultBean deleteTemplateCondition(HttpServletRequest request, HttpServletResponse response,		
			@RequestBody TemplateSave templateSave){
		if (templateSave.getTemplateSaveId() != null) {
			templateSave.setId(templateSave.getTemplateSaveId());
			return super.tipResultBean(queryTemplateService.deleteTemplateSave(templateSave.getTemplateSaveId()),DELETE,templateSave.getId());
		} 
		return super.tipResultBean(0,DELETE,"");
	}
	
	/**
	 * 根据当前登录人获得保存查询的列表
	 * @param request
	 * @param response
	 * @param queryBean
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/templateCondition/list")	
	public @ResponseBody ResultBean queryTemplateConditionList(HttpServletRequest request, HttpServletResponse response	
			){
		QueryBean queryBean = new QueryBean();
		return queryTemplateService.queryTemplateSaveBeanList(queryBean);
	}
	
	/**
	 * 根据sql生成配置
	 * @param request
	 * @param response
	 * @param queryBean
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/parse")	
	public @ResponseBody ResultBean templateParse(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody QueryBean queryBean){
		return convertQueryBean(templateParseService.parseSql(queryBean.getBindSql()));
	}
	
	/**
	 * 预览sql查询结果
	 * @param request
	 * @param response
	 * @param queryBean
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/preview")	
	public @ResponseBody ResultBean preview(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody QueryBean queryBean){
		Template template = queryBean.getTemplate();
		String sql = "";
		if (template != null) {
			StringBuffer buffer = new StringBuffer();
			buffer.append(template.getSelectArea()).append(" ").append(template.getFromArea()).append(" ")
			.append(template.getWhereArea()).append(" ").append(template.getGroupbyArea()).append(" ")
			.append(template.getOrderbyArea());
			sql = buffer.toString();
		}
		TemplateObjBean parseBean = templateParseService.parseSql(sql, true);
		QueryBean bean = null;
		if (parseBean != null && parseBean.isSuccess()) {
			queryBean.setObject(queryService.queryList(queryBean));
			queryBean.setTableViews(parseBean.getTableViews());
		} else if (!parseBean.isSuccess()) {
			return convertQueryBean(parseBean);
		}
		return convertQueryBean(queryBean);
	}
	
	/**
	 * 根据配置生成sql
	 * @param request
	 * @param response
	 * @param queryBean
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/generate")	
	public @ResponseBody ResultBean templateGenerate(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody QueryBean queryBean){
		return queryTemplateService.generateSqlByTemplate(queryBean);
	}
	/**
	 * 模型下拉框列表
	 * @param request
	 * @param response
	 * @param queryBean
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/module")	
	public @ResponseBody ResultBean templateModule(
			HttpServletRequest request, 
			HttpServletResponse response){
		return queryTemplateService.queryModuleList();
	}
	
	/**
	 * 根据模板templateId显示相关保存查询信息
	 * @param request
	 * @param response
	 * @param queryBean
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/templateCondition/show")	
	public @ResponseBody ResultBean selectTemplateConditionList(HttpServletRequest request, HttpServletResponse response,		
			@RequestBody TemplateSaveBean bean){
		QueryBean queryBean = new QueryBean();
		Template template = new Template();
		if(StringUtil.isNullOrBlank(bean.getCode())){
			return new ResultBean(false, ResultStatus.PARAM_ERROR);
		}
		template.setCode(bean.getCode());
		queryBean.setTemplate(template);
		return queryTemplateService.queryTemplateSaveBeanList(queryBean);
	}
	
	private String getContextPath(TemplateObj template) {
		if (template == null || StringUtil.isEmpty(template.getContextPath())) {
			return null;
		}
		String [] param = template.getContextPath().split("/");
		String contextPath = "";
		if (param.length > 2) {
			contextPath = param[1]+param[2];
		}
		
		return contextPath;
	}
	
	public ResultBean convertQueryBean(QueryBean querys) {
		ResultBean bean = new ResultBean();
		if (querys == null) {
			return bean;
		}
		bean.setObject(querys.getObject());
		bean.setSuccess(querys.isSuccess());
		bean.setMessage(querys.getMessage());
		return bean;
	}
	public ResultBean convertQueryBean(TemplateObjBean querys) {
		ResultBean bean = new ResultBean();
		if (querys == null) {
			return bean;
		}
		bean.setObject(querys);
		bean.setSuccess(querys.isSuccess());
		bean.setMessage(querys.getMessage());
		return bean;
	}
	
	/**
	 * 通过moduleId查询
	 * @Date        :      2017年9月21日
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/template/selectTemplateListByMouduleId")	
	public @ResponseBody ResultBean selectTemplateListByMouduleId(HttpServletRequest request, HttpServletResponse response,		
			@RequestBody Map<String,String> map){
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		Integer moduleId = null;
		if (map.containsKey("moduleId")) {
			moduleId = Integer.valueOf(map.get("moduleId"));
		}
		String code = null;
		if (map.containsKey("code")) {
			code =(String)map.get("code");
		}
		String i18nName = null;
		if (map.containsKey("i18nName")) {
			i18nName =(String)map.get("i18nName");
		}
		
		 try {
			 result.setObject(queryTemplateService.selectTemplateListByMouduleId(moduleId,code,i18nName));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
		}
		 return result;
	}
	
	/**
	 * 根据当前登录人获得保存查询的列表
	 * @param request
	 * @param response
	 * @param queryBean
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/templateCondition/listCount")	
	public @ResponseBody ResultBean queryTemplateConditionListCount(HttpServletRequest request, HttpServletResponse response	
			){
		QueryBean queryBean = new QueryBean();
		return queryTemplateService.queryTemplateSaveListAll(queryBean);
	}
	
	
	/**
	 * 修改模板
	 * @param request
	 * @param response
	 * @param template
	
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value = "/template/updateFormLayout")	
	public @ResponseBody ResultBean updateFormLayout(
			HttpServletRequest request, 
			HttpServletResponse response,		
			@RequestBody TemplateBean template){
		ResultBean result = new ResultBean();
		try {
			queryTemplateService.updateFormLayout(template);
			result.setSuccess(true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
	}
}
